<script lang="ts">
import { defineComponent } from "vue"
import {
  templateTransformNode,
  nodesTransformVNodes,
  VNodesTransformRenderFunction,
} from "../util/transform"
import type { PropType } from "vue"
import vTitle from "./vTitle.vue"
import vhome from "./vhome.vue"

const components = {
  ["v-title"]: vTitle,
  ["v-home"]: vhome,
}

const transformComponents = (globalComponents: object): object => {
  const componentsCopy: object = {}
  const whiteArray: Array<string> = ["RouterLink", "RouterView"]
  const reg = /([A-Z])/g
  for (let key in globalComponents) {
    if (!whiteArray.some(item => item == key)) {
      let changedKey = key
      changedKey = changedKey.replace(
        changedKey[0],
        changedKey[0].toLowerCase(),
      )
      changedKey = changedKey.replace(reg, function (a, b) {
        return "-" + b.toLowerCase()
      })
      componentsCopy[changedKey] = globalComponents[key]
    }
  }
  return Object.assign(componentsCopy, components)
}

const init = (template: string, globalComponents: object) => {
  if (template.trim() === "") {
    return
  }
  const nodes = templateTransformNode(template)
  const vNodes = nodesTransformVNodes(nodes)

  return VNodesTransformRenderFunction(
    vNodes,
    transformComponents(globalComponents),
  )
}
export default defineComponent({
  components,
  props: {
    template: {
      type: String as PropType<string>,
    },
  },
  mounted() {
    console.log("mounted")
  },
  updated() {
    console.log("updated")
  },
  render() {
    return init(
      `<div>${this.template}</div>`,
      this.$root?.$.appContext.components as object,
    )
  },
})
</script>
